package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.Constant;
import com.recharge.common.util.TemplateUtils;
import com.recharge.core.entity.TransactionEntity;
import com.recharge.core.mapper.TransactionMapper;
import com.recharge.domain.query.TransactionQueryDO;
import com.recharge.domain.vo.MerchantDO;
import com.recharge.domain.vo.TransactionDO;
import com.recharge.service.MerchantService;
import com.recharge.service.TransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * <h1>描述: 事务</h1>
 *
 * @author kui
 * @date 2020/8/28 11:07
 */
@Component
public class TransactionServiceImpl extends ServiceImpl<TransactionMapper, TransactionEntity> implements TransactionService {

    Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    MerchantService merchantService;

    @Value("${node.name}")
    private Integer nodeName;

    public ResultDO add(TransactionDO domain) {

        ResultDO result = new ResultSupport();

        TransactionEntity entity = new TransactionEntity();

        result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        if (entity.getAmountType() == Constant.EXPEND) {
            if (entity.getAmount() != null) {
                entity.setAmount(entity.getAmount() * -1);
            }
        }
        entity.setBeginDate(Calendar.getInstance().getTime());
        entity.setNodeName(nodeName);
        //entity.setTransactionNo(SnowflakeIdWorker.getNo());
        boolean res = false;
        try {
            res = save(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_ADD_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_ADD_ERROR.getMsg());
            return result;
        }
        domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
        return result;
    }

    public ResultDO edit(TransactionDO domain) {

        TransactionEntity entity = new TransactionEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_EDIT_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO saveUpdate(TransactionDO domain) {

        TransactionEntity entity = new TransactionEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setNodeName(nodeName);
        int res = -1;
        try {
            res = this.baseMapper.deleteById(entity.getId());
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res <= 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_EDIT_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_EDIT_ERROR.getMsg());
            return result;
        }

        try {
            res = this.baseMapper.insert(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res <= 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_EDIT_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO updateStatus(String id, int status) {

        ResultDO result = new ResultSupport();

        TransactionEntity entity = new TransactionEntity();
        entity.setId(id);
        entity.setStatus(status);

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_EDIT_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }


    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        TransactionEntity entity = null;

        try {
            entity = this.getById(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        TransactionDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    public ResultDO find(TransactionQueryDO query) {
        TransactionEntity entity = new TransactionEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<TransactionEntity> wrapper = new QueryWrapper<>(entity);
//        wrapper.lambda();
        //条件
        if (!TemplateUtils.isEmpty(query.getMerchantId())) {  //商户id
            String merchantNo;
            try {
                result = merchantService.get(query.getMerchantId());
                if (!result.isSuccess()) {
                    logger.debug("交易记录查询商户信息失败");
                    result.setErrorCode(ErrorCode.TRANSACTION_FIND_ERROR);
                    return result;
                }
                MerchantDO merchantDO = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
                merchantNo = merchantDO.getMerchantNo();
            }catch (Exception e){
                logger.debug("交易记录查询商户信息失败");
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.TRANSACTION_FIND_ERROR);
                return result;
            }
            wrapper.lambda().eq(TransactionEntity::getMerchantNo, merchantNo);
        }
        if (!TemplateUtils.isEmpty(query.getTransactionNo())) {
            wrapper.lambda().eq(TransactionEntity::getTransactionNo, query.getTransactionNo());
        }
        if (!TemplateUtils.isEmpty(query.getType())) {
            wrapper.lambda().eq(TransactionEntity::getType, query.getType());
        }
        if (!TemplateUtils.isEmpty(query.getAmountType())) {
            wrapper.lambda().eq(TransactionEntity::getAmountType, query.getAmountType());
        }
        if (!TemplateUtils.isEmpty(query.getStatus())) {
            wrapper.lambda().eq(TransactionEntity::getStatus, query.getStatus());
        }
        if (!TemplateUtils.isEmpty(query.getStartTime())) {
            wrapper.lambda().ge(TransactionEntity::getBeginDate, query.getStartTime());
        }
        if (!TemplateUtils.isEmpty(query.getEndTime())) {
            wrapper.lambda().lt(TransactionEntity::getBeginDate, query.getEndTime());
        }

        Page<TransactionEntity> page = new Page<>(query.getCurrentPage(), query.getPageSize());
        IPage<TransactionEntity> iPage = null;

        try {
            iPage = baseMapper.selectInfoPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.TRANSACTION_FIND_ERROR);
            logger.debug("error code：" + ErrorCode.TRANSACTION_FIND_ERROR.getCode() + " msg" + ErrorCode.TRANSACTION_FIND_ERROR.getMsg());
            return result;
        }
        List<TransactionDO> domainList = getDomainList(iPage.getRecords());

        PageDO<TransactionDO> pageDO = new PageDO<>();
        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(domainList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);

        return result;
//        ResultDO result = new ResultSupport();
//        Page<TransactionEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
//        IPage<TransactionEntity> iPage;
//        try {
//            Map<String, Object> map = MapTool.bean2Map(query);
//            // 分页查询
//            iPage = baseMapper.selectListPage(page, map);
//        } catch (Exception e) {
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//            logger.debug("分页查询交易记录失败" + e.getMessage());
//            return result;
//        }
//
//        // 获取查询信息
//        List<TransactionDO> doList = getDomainList(iPage.getRecords());
//
//        if(doList != null && !doList.isEmpty()){
//            doList.forEach( item -> {
//                MerchantEntity merchantEntity = merchantService.getOne(Wrappers.<MerchantEntity>lambdaQuery().eq(MerchantEntity::getMerchantNo, item.getMerchantNo()));
//                if(merchantEntity != null){
//                    item.setMerchantName(merchantEntity.getMerchantName());
//                }
//            });
//        }
//
//        PageDO<TransactionDO> pageDO = new PageDO<>();
//
//        // 设置分页信息
//        pageDO.setCurrentPage(iPage.getCurrent());
//        pageDO.setPageCount(iPage.getPages());
//        pageDO.setPageSize(iPage.getSize());
//        pageDO.setRowCount(iPage.getTotal());
//        pageDO.setData(doList);
//
//        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
//        return result;
    }

    private TransactionDO getDomain(TransactionEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if (entity == null) return null;
        TransactionDO domain = new TransactionDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<TransactionDO> getDomainList(List<TransactionEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<TransactionDO> doList = new ArrayList<TransactionDO>();

        //判断传入的list的集合的size是否大于0
        if (list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for (TransactionEntity entity : list) {

                TransactionDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if (domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
